package utils

import (
	"encoding/json"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"lin6xcom/src/models"
	"os"
	"xorm.io/xorm"
)

type Config struct {
	Host     string `json:"host"`
	Port     int    `json:"port"`
	Username string `json:"username"`
	Password string `json:"password"`
	Database string `json:"database"`
}

func GetConfig() (config Config) {
	filePath := "./src/config/db.config.json"
	file, err := os.Open(filePath)
	if err != nil {
		fmt.Println("读取配置文件失败")
	}
	defer file.Close()
	decoder := json.NewDecoder(file)
	var data Config
	err1 := decoder.Decode(&data)
	if err1 != nil {
		fmt.Println("解析配置文件失败")
	}
	return data
}
func LinkDB() (db *xorm.Engine) {
	config := GetConfig()
	baseUrl := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8", config.Username, config.Password, config.Host, config.Port, config.Database)
	//fmt.Println(baseUrl)
	db, err := xorm.NewEngine("mysql", baseUrl)
	if err != nil {
		fmt.Println("数据库连接失败.................")
		fmt.Println("ERROR", err)
		panic(err)
		return
	} else {
		fmt.Println("数据库连接成功++.................")
	}

	if err := db.Sync2(new(models.Article), new(models.User), new(models.Category), new(models.Tokens)); err != nil {
		fmt.Println("数据库迁移失败.................")
		fmt.Println("ERROR", err)

	} else {
		fmt.Println("数据库迁移成功..................")
	}

	return db
}
